package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //先计算日期区间datelist
        List<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            datelist.add(begin);
        }

        //在计算每日营业额turnoverListOrders,状态为已完成，时间为上述区间
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : datelist) {
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("begin",begintime);
            map.put("end",endtime);
            map.put("status",5);

            Double turnover =  orderMapper.sumAmount(map);
            turnover = turnover == null ? 0 : turnover;

            turnoverList.add(turnover);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(datelist,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //dateList先创建日期集合存放日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //totalUserList用户总量集合
        List<Integer> totalUserList = new ArrayList<>();
        //newUserList新增用户集合
        List<Integer> newUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            //将起止时间放入map，传给数据层作为时间区间
            Map map = new HashMap();
            map.put("end",endtime);
            Integer totalUser =  userMapper.getUserStatistics(map);//总用户人数只关心截止时间，所以先进行查询
            totalUserList.add(totalUser);
            //使用动态sql语句，有截止无起始则为总用户数量
            map.put("begin",begintime);
            Integer newUser = userMapper.getUserStatistics(map);//新增用户数量关系起始和截止时间
            newUserList.add(newUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     * 订单数据统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //dateList先创建日期集合存放日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //orderCountList    每天订单总量集合
        List<Integer> orderCountList = new ArrayList<>();
        //validOrderCountList   每天有效订单量集合
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //获取当前天所在区间
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",begintime);
            map.put("end",endtime);
            //获取每天订单总量  select count(id) from orders where order_time < ? and order_time > ?
            Integer sumOrders = orderMapper.getOrderStatistics(map);
            //获取每天有效订单量 select count(id) from orders where order_time < ? and order_time > ? and status = 5
            map.put("status",Orders.COMPLETED);
            Integer validOrders = orderMapper.getOrderStatistics(map);

            orderCountList.add(sumOrders);
            validOrderCountList.add(validOrders);
        }
        //总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //总有效订单数
//        Integer validOrderCount = 0;
//        for (Integer validCount : validOrderCountList) {
//            validOrderCount += validCount;
//        }
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }


    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //商品名称列表，以逗号分隔，例如：鱼香肉丝,宫保鸡丁,水煮鱼     nameList;
        List<String> nameList = new ArrayList<>();
        //销量列表，以逗号分隔，例如：260,215,200         numberList;
        List<Integer> numberList = new ArrayList<>();

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end",endTime);
        map.put("status", Orders.COMPLETED);
        List<OrderDetail> orderDetails = orderDetailMapper.getTop10(map);
//      nameList = orderDetails.stream().map(OrderDetail::getName).collect(Collectors.toList());
//      numberList = orderDetails.stream().map(OrderDetail::getNumber).collect(Collectors.toList());
        for (OrderDetail orderDetail : orderDetails) {
            nameList.add(orderDetail.getName());
            numberList.add(orderDetail.getNumber());
        }
        //将集合转为字符串  StringUtils.join(集合，分割符)
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    @Override
    public void export(HttpServletResponse response){
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin,LocalTime.MIN),
                                                                        LocalDateTime.of(dateEnd,LocalTime.MAX));
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue("时间:" + dateBegin + "至" + dateEnd);

            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                LocalDateTime date1 = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime date2 = LocalDateTime.of(date, LocalTime.MAX);
                BusinessDataVO dataVO = workspaceService.getBusinessData(date1, date2);

                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(dataVO.getTurnover());
                row.getCell(3).setCellValue(dataVO.getValidOrderCount());
                row.getCell(4).setCellValue(dataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(dataVO.getUnitPrice());
                row.getCell(6).setCellValue(dataVO.getNewUsers());
            }
            //获得输出流，将excel文件写入
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
